package com.zzsoft.util;/**
 * Created by zhanghb on 2019/9/3.
 */

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description
 * @Author Zhanghb
 * @Date
 */
@Slf4j
public class SocketUtil {
    private static Map<String,Channel> channelStore=new ConcurrentHashMap<>();
    public static void add(String clientId,Channel Channel){
        channelStore.put(clientId,Channel);
        log.info("有新连接加入，clientId："+clientId+"---当前连接总数为："+channelStore.size());
    }
    public static Channel get(String clientId){
        return channelStore.get(clientId);
    }
    public static void remove(Channel Channel){
        for (Map.Entry entry:channelStore.entrySet()){
            if (entry.getValue()==Channel){
                String channelId = (String)entry.getKey();
                channelStore.remove(channelId);
                log.warn("有连接断开，clientId："+channelId+"---当前连接总数为："+channelStore.size());
            }
        }
    }

    /**
     * 给客户端发送消息
     * @param key
     * @param msg
     */
    public static void sendMsg(String key,String msg){
        Channel channel = get(key);
        log.info("channel: "+channel);
            if(channel!=null) {
                channel.writeAndFlush(msg);
            }

    }

    /**
     * 给客户端发送消息
     * @param clientId
     * @param msg
     */
    public static void sendMsgToClient(String clientId,final String msg) {
        try {
            Channel channel = channelStore.get(clientId);
            if (null != channel && channel.isActive()) {
                channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            log.error("chat msg  发送失败, msg is : {}     cause: ", msg, future.cause());
                        }
                    }
                });
            }
        } catch (Exception e) {
            log.error("chat msg 发送失败 wrapper, msg is : {}", e);
        }
    }

    /**
     * 给所有客户端发送消息
     * @param msg
     */
    public static void sendMsgToAllClient(final String msg) {
        try {
            for (Map.Entry entry:channelStore.entrySet()){
                if (!StringUtils.isEmpty(entry.getKey())){
                    sendMsgToClient((String)entry.getKey(),msg);
                }
            }
        } catch (Exception e) {
            log.error("chat msg 发送失败 wrapper, msg is : {}", e);
        }
    }
}
